﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace knn_r1
{

    public partial class Form1 : Form
    {
        List<String[]> D;
        public Form1()
        {
            InitializeComponent();
            D = new List<string[]>();
        }
        private double cellCompare(String s1, String s2)
        {
            double a, b;
            double.TryParse(s1, out a);
            double.TryParse(s2, out b);
            return (a - b) * (a - b);

        }
        /*
         * r1: test row
         * r2: training row
         */


        private double rowCompare(String[] r1, String[] r2)
        {
            double diff = 0;
            for (int i = 0; i <= r1.Length - 1; i++)
            {
                double kq = cellCompare(r1[i], r2[i]);
                diff = diff + kq;
            }
            return Math.Sqrt(diff);
        }
        private void btnfile_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();
                dataGridView1.Refresh();
                D.Clear();
                openFileDialog1.Filter = "File *.csv|*.csv";
                openFileDialog1.ShowDialog();
                String filename = openFileDialog1.FileName;

                if (openFileDialog1.CheckFileExists == false)
                    openFileDialog1.ShowDialog();
                txtfilename.Text = Path.GetFileName(filename);

                StreamReader sr = new StreamReader(filename);
                String[] attribute = sr.ReadLine().Split(','); // cac thuoc tinh

                foreach (String s in attribute)
                    dataGridView1.Columns.Add(s, s);
                int iRow = 0;
                while (!sr.EndOfStream)
                {
                    String[] instance = sr.ReadLine().Split(',');
                    D.Add(instance);
                    dataGridView1.Rows.Add(D[iRow++]);
                }
                lbsoMau.Text = D.Count.ToString();
                lbsoThuocTinh.Text = D[0].Length.ToString();
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("File Chưa Được Chọn");
                openFileDialog1.ShowDialog();
            }
        }
        private void sort(int[] iarr)
        {
            for (int i = 0; i <= iarr.Length - 2; i++)
                for (int j = i + 1; j <= iarr.Length - 1; j++)
                    if (iarr[i] < iarr[j])
                    {
                        int temp = iarr[i];
                        iarr[i] = iarr[j];
                        iarr[j] = temp;
                    }

        }
        private int tanSuat(String[] arr, String x)
        {
            int ts = 0;
            for (int i = 0; i < arr.Length; i++)
                if (x.Equals(arr[i]))
                    ts++;
            return ts;
        }
        private void txtnhapMau_Click(object sender, EventArgs e)
        {
            try
            {
                int k = int.Parse(txtk.Text);
               String newMau = txtmauMoi.Text + ",?";
                String[] newInstance = newMau.Split(',');
                if (newInstance.Length != D[0].Length)
                {
                    MessageBox.Show("Tap dau vao khong hop le");
                    return;
                }
                //D.Add(newInstance);
                //dataGridView1.Rows.Add(newInstance);
                //dataGridView1.Rows[dataGridView1.Rows.Count - 1].DefaultCellStyle.BackColor = Color.RoyalBlue;

                lstRow lstRow = new lstRow();
                for (int i = 0; i < D.Count; i++)
                {
                    double kq = this.rowCompare(newInstance, D[i]);
                    oRow r = new oRow();
                    r.Index = i;
                    r.Distance = kq;
                    lstRow.Lst.Add(r);
                }
                lstRow.Sort();
                if (k > D.Count)
                    k = D.Count;
                String[] lop = new String[k];
                for (int i = 0; i < k; i++)
                {
                    int index = lstRow.Lst[i].Index;
                    lop[i] = D[index][D[0].Length - 1];

                }
                String lc = lop[0];
                for (int i = 0; i < k; i++)
                    if (tanSuat(lop, lop[i]) > tanSuat(lop, lc))
                        lc = lop[i];
                newInstance[newInstance.Length - 1] = lc; // gan nhan cho mau can phan lop
                dataGridView1.Rows.Add(newInstance); // them mau moi vao training set
                D.Add(newInstance);                  //
                lbsoMau.Text = D.Count.ToString();
                dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
                dataGridView1.Rows[dataGridView1.RowCount -2].DefaultCellStyle.BackColor = Color.White;
                dataGridView1[dataGridView1.ColumnCount - 1, dataGridView1.RowCount - 2].Style.ForeColor = Color.Black;
                dataGridView1.Rows[dataGridView1.RowCount - 1].DefaultCellStyle.BackColor = Color.Beige;
                dataGridView1[dataGridView1.ColumnCount - 1, dataGridView1.RowCount - 1].Style.ForeColor = Color.Red;
                
            }
            catch (ArgumentOutOfRangeException ex)
            {
                MessageBox.Show("Không có Training Set, không thể chạy thuật toán");
            }
        }
        private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            try
            {
                D.RemoveAt(e.RowIndex);
                lbsoMau.Text = D.Count.ToString();
                lbsoThuocTinh.Text = D[0].Length.ToString();
            }
            catch (ArgumentOutOfRangeException ex) {
                MessageBox.Show("Training set rỗng");
            }
        }

        private void txtk_Click(object sender, EventArgs e)
        {
            txtk.Clear();
        }

        private void txtfilename_DoubleClick(object sender, EventArgs e)
        {
            btnfile_Click(sender, e);
        }

      
    }
}

class oRow
{
    int index;

    public int Index
    {
        get { return index; }
        set { index = value; }
    }
    double distance;

    public double Distance
    {
        get { return distance; }
        set { distance = value; }
    }
}

class lstRow
{
    private List<oRow> lst;

    internal List<oRow> Lst
    {
        get { return lst; }
        set { lst = value; }
    }
    public lstRow()
    {
        lst = new List<oRow>();
    }
    public void Sort()
    {
        for (int i = 0; i <= lst.Count - 1; i++)
            for (int j = i + 1; j <= lst.Count - 1; j++)
                if (lst[i].Distance > lst[j].Distance)
                {
                    oRow temp = lst[i];
                    lst[i] = lst[j];
                    lst[j] = temp;
                }
    }
}

